import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token,user=None,request=None):
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username,
    }

def get_user_by_account(account):
    if re.match(r'1[3-8]\d{9}$', account):
        try:
            user = User.objects.get(mobile=account)
            return user
        except User.DoesNotExist:
            return None
    else:
        try:
            user = User.objects.get(usernamr=account)
            return user
        except User.DoesNotExist:
            return None


class UsernameMobileAuth(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user